<template>
  <div class="intelligent-search-container">
    <el-card class="search-card" :body-style="{ padding: '0' }">
      <div class="search-header">
        <h2 class="search-title">智能搜题</h2>
        <p class="search-subtitle">上传图片，自动识别并解答题目</p>
      </div>

      <el-form ref="searchForm" :model="searchForm" label-width="120px" class="search-form">
        <div class="upload-wrapper">
          <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            multiple
            accept="image/png, image/jpeg, image/jpg"
          >
            <div v-if="!isLoading" class="upload-box">
              <i class="el-icon-upload upload-icon"></i>
              <div class="upload-text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="upload-tip">仅支持上传 JPG 或 PNG 格式的图片</div>
            </div>
            <div v-else class="upload-loading">
              <el-spinner size="large" class="loading-spinner"></el-spinner>
              <div class="loading-text">正在识别图片...</div>
            </div>
          </el-upload>
        </div>
      </el-form>
      
      <div v-if="ocrResult && !isQuestionLoading" class="ocr-result">
        <h3 class="result-title">题目：</h3>
        <div class="result-content question-content">
          <pre>{{ ocrResult }}</pre>
        </div>
      </div>
      
      <div v-if="isQuestionLoading" class="question-loading">
        <el-spinner type="fading-circle" size="large" class="loading-spinner"></el-spinner>
        <div class="loading-text">正在解答题目...</div>
      </div>

      <div v-if="questionResult.length > 0 && !isQuestionLoading" class="question-result">
        <h3 class="result-title">解题结果：</h3>
        <div class="result-content answer-content" v-html="questionResult[0].html"></div>
      </div>

      <div v-if="error" class="error-message">
        <el-alert :title="error" type="error" show-icon :closable="false"></el-alert>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { marked } from 'marked';

export default {
  name: 'Intelligent408Search',
  setup() {
    const searchForm = ref({});
    const ocrResult = ref(null);
    const questionResult = ref([]);
    const error = ref(null);
    const uploadUrl = ref('http://localhost:5000/ocr');
    const uploadHeaders = ref({
      'Authorization': `Bearer ${localStorage.getItem('token')}`,
    });
    const selectedModel = ref('DeepSeek-V3');
    const isLoading = ref(false); // 图片上传和OCR加载状态
    const isQuestionLoading = ref(false); // 题目解答加载状态

    const handleUploadSuccess = async (response, file) => {
      isLoading.value = true;
      if (response && response.result) {
        ocrResult.value = response.result.map(item => item.text).join('\n');
        error.value = null;
        isLoading.value = false;
        await askQuestion(ocrResult.value);
      } else {
        error.value = 'OCR 识别失败，请稍后再试';
        isLoading.value = false;
      }
    };

    const handleUploadError = (error, file) => {
      console.error('Upload error:', error);
      error.value = '上传失败，请稍后再试';
      isLoading.value = false;
    };

    const beforeUpload = (file) => {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isImage) {
        ElMessage.error('仅支持上传 JPG 或 PNG 格式的图片');
        return false;
      }
      return true;
    };

    const askQuestion = async (questionText) => {
      if (!questionText) return;
      
      isQuestionLoading.value = true;
      questionResult.value = [];
      
      try {
        const dialogId = "1";
        const response = await axios.post('http://localhost:8080/aichat/chat', {
          dialogId: dialogId,
          ask: questionText,
          mode: "2",
          model: selectedModel.value
        }, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
          },
        });

        if (typeof response.data === 'object' && response.data !== null) {
          const htmlContent = marked(response.data.response || '');
          questionResult.value = [{ html: htmlContent }];
          error.value = null;
        } else {
          error.value = '解题失败，请稍后再试';
        }
      } catch (error) {
        console.error('Error asking question:', error);
        if (error.response && error.response.status === 404) {
          error.value = '解题接口未找到，请检查后端服务';
        } else {
          error.value = '解题失败，请稍后再试';
        }
      } finally {
        isQuestionLoading.value = false;
      }
    };
    
    onMounted(() => {
      // 配置marked解析器
      marked.setOptions({
        breaks: true,
        gfm: true
      });
    });

    return {
      searchForm,
      ocrResult,
      questionResult,
      error,
      uploadUrl,
      uploadHeaders,
      handleUploadSuccess,
      handleUploadError,
      beforeUpload,
      isLoading,
      isQuestionLoading,
      askQuestion
    };
  },
};
</script>

<style scoped lang="scss">
$primary-color: #4f46e5;        // 主色调 - 深紫色
$primary-light: #818cf8;       // 主色浅色 - 浅紫色
$secondary-color: #10b981;     // 成功色 - 绿色
$error-color: #ef4444;         // 错误色 - 红色
$bg-color: #f9fafb;            // 背景色
$card-bg: #ffffff;             // 卡片背景色
$text-color: #1f2937;          // 文本主色
$text-secondary: #6b7280;      // 次要文本色

.intelligent-search-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30px 20px;
  background-color: $bg-color;
  min-height: 100vh;
  width: 100%;
}

.search-card {
  width: 100%;
  max-width: 800px;
  margin-bottom: 30px;
  background-color: $card-bg;
  border-radius: 16px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);
  transition: all 0.3s ease;
  overflow: hidden;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }
}

.search-header {
  text-align: center;
  padding: 30px 20px;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, $primary-color 0%, $primary-light 100%);
  color: white;
  
  .search-title {
    color: white;
  }
  
  .search-subtitle {
    color: rgba(255, 255, 255, 0.8);
  }
}

.search-title {
  font-size: 28px;
  margin: 0;
  font-weight: 700;
  line-height: 1.3;
}

.search-subtitle {
  font-size: 14px;
  margin: 8px 0 0;
  line-height: 1.5;
}

.search-form {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  padding: 20px;
}

.upload-wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
  max-width: 600px;
}

.upload-demo {
  width: 100%;
  
  .el-upload-list {
    position: static !important;
    margin-top: 10px;
  }
  
  .el-upload-list__item {
    margin: 0 !important;
    padding: 0 !important;
    border: none !important;
    background: transparent !important;
  }
  
  .el-upload-list__item.is-success .el-upload-list__item-status-label {
    right: auto !important;
    left: 50% !important;
    transform: translateX(-50%) !important;
    top: 100% !important;
    margin-top: 5px !important;
  }
}

.upload-box {
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  padding: 40px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: $primary-color;
    background-color: rgba($primary-color, 0.03);
  }
}

.upload-loading {
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 40px 20px;
  text-align: center;
  background-color: #f9fafb;
}

.upload-icon {
  font-size: 40px;
  margin-bottom: 15px;
  color: $primary-color;
}

.upload-text {
  font-size: 16px;
  margin-bottom: 10px;
  color: $text-color;
}

.upload-text em {
  color: $primary-color;
  font-style: normal;
  font-weight: 500;
}

.upload-tip {
  font-size: 14px;
  margin-top: 10px;
  color: $text-secondary;
}

.loading-spinner {
  margin-bottom: 15px;
  color: $primary-color;
}

.loading-text {
  font-size: 16px;
  color: $text-secondary;
}

.ocr-result, .question-result {
  margin: 20px;
  border-radius: 12px;
  padding: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.result-title {
  font-size: 18px;
  color: $text-color;
  margin: 0;
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 600;
}

.result-content {
  padding: 20px;
  line-height: 1.8;
  font-size: 16px;
  color: $text-color;
}

.question-content {
  background-color: #f9fafb;
  white-space: pre-wrap;
  font-family: 'Inter', system-ui, sans-serif;
}

.answer-content {
  background-color: white;
  white-space: pre-wrap;
  
  // 美化markdown渲染的内容
  h1, h2, h3, h4, h5, h6 {
    color: $text-color;
    margin-top: 24px;
    margin-bottom: 16px;
    font-weight: 600;
    line-height: 1.25;
  }
  
  h2 {
    padding-bottom: 0.3em;
    font-size: 1.5em;
    border-bottom: 1px solid #eaecef;
  }
  
  h3 {
    font-size: 1.25em;
  }
  
  p {
    margin-bottom: 16px;
  }
  
  ul, ol {
    padding-left: 2em;
    margin-bottom: 16px;
  }
  
  li {
    margin-bottom: 8px;
  }
  
  pre {
    padding: 16px;
    overflow: auto;
    font-size: 85%;
    line-height: 1.45;
    border-radius: 6px;
    margin-bottom: 16px;
    tab-size: 4;
    background-color: #f6f8fa;
    border: 1px solid #e1e4e8;
  }
  
  code {
    padding: 0.2em 0.4em;
    margin: 0;
    font-size: 85%;
    background-color: rgba(175, 184, 193, 0.2);
    border-radius: 6px;
    font-family: SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace;
  }
  
  blockquote {
    margin-left: 0;
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
    margin-bottom: 16px;
  }
  
  table {
    border-collapse: collapse;
    margin-bottom: 16px;
    display: block;
    width: 100%;
    overflow: auto;
  }
  
  th, td {
    padding: 6px 13px;
    border: 1px solid #dfe2e5;
  }
  
  th {
    font-weight: 600;
  }
  
  tr {
    background-color: #fff;
    border-top: 1px solid #c6cbd1;
  }
  
  tr:nth-child(2n) {
    background-color: #f6f8fa;
  }
}

.question-loading {
  margin: 20px;
  text-align: center;
  padding: 40px 20px;
}

.error-message {
  margin: 20px;
}

.el-upload__input {
  display: none;
}
</style>